package com.qiku.web.servlet;

import com.alibaba.fastjson.JSON;
import com.qiku.dao.UserDao;
import com.qiku.dao.impl.UserDaoImpl;
import com.qiku.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/checkName")
public class CheckNameServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        Map<String,Object> map = new HashMap<>();
        String result = "";
        if (username.equals("")){
            map.put("regMsg","用户名不能为空");
            result = JSON.toJSONString(map);
        }else {
            User user = userDao.findUserByName(username);
            if (user == null){
                map.put("regMsg","用户名可以使用");
                result = JSON.toJSONString(map);
            }else {
                map.put("regMsg","用户名已被占用");
                result = JSON.toJSONString(map);
            }
        }
        resp.getWriter().println(result);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
